const AdminUserSchema = require('../entity/user/adminuser');
const tokenService = require('./token');
const serviceError = require('../module/error/svcerror');
const UserBase = require('../entity/user/userbase');

/**
 * 管理员登录
 * @param username
 * @param password
 * @returns {Promise<*>}
 */
async function login (username, password) {
    const AdminUserEntity = new AdminUserSchema();
    const adminUser = await AdminUserEntity.findByAccount(username, password);
    if (!adminUser) throw new serviceError.AdminUserNotExist('账号密码错误');
    if (!adminUser.isEnable) throw new serviceError.AdminUserNotExist('账号已被停用，请联系管理员！');
    return tokenService.generateAdminSiteToken({ adminId: adminUser._id }, 86400);
}

/**
 * 获取管理员信息
 * @param adminUserId
 * @param schoolName
 * @returns {Promise<{area: (Query<{name: {type: *, required: boolean}|*, id: any}, Object>|[{name: *, id: *}]), name: *, isSuperAdmin: boolean, avatar: *}>}
 */
async function getAdminInfo (adminUserId, schoolName) {
    const adminUserData = await new AdminUserSchema().getModel().findById(adminUserId);
    return {
        phone: adminUserData.phone,
        name: adminUserData.nickname,
        avatar: adminUserData.avatar,

        isSuperAdmin: adminUserData.isSuperAdmin,
        roles: adminUserData.roles,
        areaId: adminUserData.areaId
    };
}

/**
 * 获取用户列表
 * @param offset,rows
 * @param rows
 * @param query
 * @body query
 * @returns {Promise<{area: (Query<{name: {type: *, required: boolean}|*, id: any}, Object>|[{name: *, id: *}]), name: *, isSuperAdmin: boolean, avatar: *}>}
 */
async function getUserList (offset, rows, query) {
    offset = parseInt(offset);
    rows = parseInt(rows);
    query = query || {};
    if (query.authAreaId) {
        query.authAreaId = UserBase.toObjectId(query.authAreaId);
    }
    if (query.vip_id) {
        query.vip_id = UserBase.toObjectId(query.vip_id);
    }
    const userModel = new UserBase().getModel();
    const res = await userModel.aggregate([
        { $match: query },
        {
            $lookup: {
                from: 'promote_record',
                localField: '_id',
                foreignField: 'customId',
                as: 'promoterRecord'
            }
        },
        {
            $unwind: {
                path: '$promoterRecord',
                preserveNullAndEmptyArrays: true
            }

        },
        {
            $lookup: {
                from: 'user_base',
                localField: 'promoterRecord.promoterId',
                foreignField: '_id',
                as: 'promoter'
            }
        },
        {
            $unwind: {
                path: '$promoter',
                preserveNullAndEmptyArrays: true
            }

        },
        {
            $lookup: {
                from: 'credit_amount',
                localField: '_id',
                foreignField: 'userId',
                as: 'creditAmount'
            }
        },
        {
            $unwind: {
                path: '$creditAmount',
                preserveNullAndEmptyArrays: true
            }

        },
        {
            $sort: {
                createTime: -1
            }
        },

        {
            $facet: {
                total: [
                    { $count: 'total' }
                ],
                data: [
                    { $skip: offset },
                    { $limit: rows }
                ]
            }
        }

    ]);
    const count = res[0].total[0] ? res[0].total[0].total : 0;
    const data = res[0].data;
    return {
        count,
        data
    };
}

async function isSuperAdmin (adminId) {
    const adminUserData = await new AdminUserSchema().getModel().findById(adminId);
    return !!adminUserData.isSuperAdmin;
}

// 查询信用金用户
async function getCreditUserList (offset, rows, query) {
    offset = parseInt(offset);
    rows = parseInt(rows);
    query = query || {};
    if (query.authAreaId) {
        query.authAreaId = UserBase.toObjectId(query.authAreaId);
    }

    const userModel = new UserBase().getModel();
    const res = await userModel.aggregate([
        { $match: query },
        {
            $lookup: {
                from: 'credit_amount',
                localField: '_id',
                foreignField: 'userId',
                as: 'creditInfo'
            }
        },
        {
            $unwind: {
                path: '$creditInfo',
                preserveNullAndEmptyArrays: false
            }
        },
        {
            $sort: {
                createTime: -1
            }
        },
        {
            $facet: {
                total: [
                    { $count: 'total' }
                ],
                data: [
                    { $skip: offset },
                    { $limit: rows }
                ]
            }
        }
    ]);
    const count = res[0].total[0] ? res[0].total[0].total : 0;
    const data = res[0].data;
    return { count, data };
}

module.exports = {
    login,
    getAdminInfo,
    isSuperAdmin,
    getUserList,
    getCreditUserList
};
